package com.lixiaoyi.utils;

import com.lixiaoyi.entity.Department;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author 李小毅
 * @Description 生成部门树
 * @Date 2022-07-03
 */

public class DepartmentTree {


    public static List<Department> makeDepartmentTree(List<Department> departmentList,
                                                      Long pid){
        // 创建集合保存部门信息
        List<Department> list = new ArrayList<Department>();
        // 如果departmentList 部门列表不空 使用部门列表 否则创建集合对象
        Optional.ofNullable(departmentList).orElse(new ArrayList<Department>())
                .stream().filter(item -> item != null && item.getPid() == pid)
                .forEach(item ->{
                    // 创建部门对象
                    Department department = new Department();
                    // 复制属性
                    BeanUtils.copyProperties(item, department);
                    // 获取每个item的下级部门 递归生成部门数
                    List<Department> children = makeDepartmentTree(departmentList, item.getId());
                    // 设置子部门
                    department.setChildren(children);
                    // 将部门对象添加到集合中
                    list.add(department);
                });
        //System.out.println("DepartmentTree");
        //System.out.println(list);
        return list;
    }
}
